import React, { Component } from "react";
import { connect } from "react-redux";
import { Card, Button, Form, Input, Select } from "antd";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { reqCategoryList, reqProductAdd, reqProductInfoById, reqProductUpdate } from "../../api";
import PicturesWall from "./pricture_upload";
import EditorConvertToHTML from "./editor";
import { BASE_IMG_URL } from "../../config/index";
const { Option } = Select;
const { Item } = Form;


@connect(
    state => ({
        productInfo: state.productInfo
    }),
    {}
)
class ProductAddOrUpdate extends Component {

    state = {
        categoryList: [],
        detail: "",//商品详情
        desc: "",//商品描述
        imgs: [],//商品图片
        name: "",//商品名称
        price: "",//商品价格
        categoryId: "",//商品分类id
        pCategoryId: "",
        status: "",
        _id: "",//商品id
        type: "add"
    }

    pictureWallRef = React.createRef();
    editorRef = React.createRef();
    formRef = React.createRef();


    onFinishCallback = async (v) => {
        let paramsObj = { ...v, pCategoryId: 0, imgs: this.pictureWallRef.current.getImgs(), detail: this.editorRef.current.getContent() };
        let result
        if (this.state.type === "add") {
            result = await reqProductAdd(paramsObj);
        } else {
            let {_id,status,categoryId} = this.state;
            result = await reqProductUpdate({_id,status,categoryId,...paramsObj});
        }
        if (result)
            this.props.history.replace("/admin/products/product");
    }

    onFinishFailedCallback = (e) => {
        alert("请检查输入内容");
    }

    priceValidator = (_, value) => {
        if (value < 0) {
            return Promise.reject("价格不能小于0");
        } else {
            return Promise.resolve();
        }
    }

    categoryValidator = (_, value) => {
        if (value === "def") {
            return Promise.reject("请选择分类");
        } else {
            return Promise.resolve();
        }
    }

    getCategoryList = async (type = "add", product = {}) => {
        let categoryList = await reqCategoryList();
        if (type === "update") {
            this.setState({ ...product, type, categoryList: [...categoryList] });
            this.formRef.current.setFieldsValue({
                "name": this.state.name,
                "desc": this.state.desc,
                "price": this.state.price,
                "categoryId": this.state.categoryId
            });
            let imgs = product.imgs.map((v, i) => {
                return { uid: -i, name: v, url: BASE_IMG_URL + v }
            })
            this.pictureWallRef.current.setImgs(imgs);
            this.editorRef.current.setContent(product.detail);
        } else {
            this.setState({ categoryList: [...categoryList] })
        }
    }

    /**
         * 根据商品id获取商品详情，详情中的分类只有分类id，所以需要再获取一下分类
         * @param {商品id} productId 
         */
    getProductInfo = async (productId) => {
        let product = await reqProductInfoById(productId);
        this.getCategoryList("update", product);
    }

    componentDidMount() {
        if (this.props.match.params.id) {
            if (Object.keys(this.props.productInfo).length === 0) {
                this.getProductInfo(this.props.match.params.id);
            } else {
                this.getCategoryList("update", this.props.productInfo);
            }
        } else {
            this.getCategoryList()
        }
    }

    render() {
        return (
            <Card
                title={
                    <div>
                        <Button icon={<ArrowLeftOutlined />} type="link" onClick={() => { this.props.history.goBack() }} />
                        <span>商品{(this.state.type === "update") ? "修改" : "添加"}</span>
                    </div>
                }
            >
                <Form
                    ref={this.formRef}
                    labelCol={{ span: 2 }}
                    wrapperCol={{ span: 9 }}
                    onFinish={this.onFinishCallback}
                    onFinishFailed={this.onFinishFailedCallback}
                >
                    <Item
                        name="name"
                        label="商品名称"
                        rules={[{ required: true, message: "商品名称不能为空" }]}
                    >
                        <Input placeholder="请输入商品名称" />
                    </Item>
                    <Item
                        name="desc"
                        label="商品描述"
                        rules={[{ required: true, message: "商品描述不能为空" }]}
                    >
                        <Input placeholder="请输入商品名称" />
                    </Item>
                    <Item
                        name="price"
                        label="商品价格"
                        rules={[{ required: true, message: "价格不能为空" }, { validator: this.priceValidator }]}
                    >
                        <Input type="number" addonAfter="元" addonBefore="￥" />
                    </Item>
                    <Item
                        initialValue="def"
                        name="categoryId"
                        label="商品分类"
                        rules={[{ required: true, message: "请选择分类" }, { validator: this.categoryValidator }]}
                    >
                        <Select >
                            <Option value="def">请选择分类</Option>
                            {
                                this.state.categoryList.map(v => {
                                    return <Option key={v._id} value={v._id}>{v.name}</Option>
                                })
                            }
                        </Select>
                    </Item>
                    <Item wrapperCol={{ span: 14 }}
                        name="imgs"
                        label="商品图片"
                    >
                        <PicturesWall ref={this.pictureWallRef} />
                    </Item>
                    <Item
                        name="detail"
                        label="商品详情"
                        wrapperCol={{ span: 18 }}
                    >
                        <EditorConvertToHTML ref={this.editorRef} />
                    </Item>
                    <Item>
                        <Button type="primary" htmlType="submit">提交</Button>
                    </Item>
                </Form>
            </Card>
        );
    }
}
export default ProductAddOrUpdate;